// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "FLTWebViewFlutterPlugin.h"
#import "FWFGeneratedWebKitApis.h"
#import "FWFHTTPCookieStoreHostApi.h"
#import "FWFInstanceManager.h"
#import "FWFNavigationDelegateHostApi.h"
#import "FWFObjectHostApi.h"
#import "FWFPreferencesHostApi.h"
#import "FWFScriptMessageHandlerHostApi.h"
#import "FWFScrollViewDelegateHostApi.h"
#import "FWFScrollViewHostApi.h"
#import "FWFUIDelegateHostApi.h"
#import "FWFUIViewHostApi.h"
#import "FWFURLCredentialHostApi.h"
#import "FWFURLHostApi.h"
#import "FWFUserContentControllerHostApi.h"
#import "FWFWebViewConfigurationHostApi.h"
#import "FWFWebViewHostApi.h"
#import "FWFWebsiteDataStoreHostApi.h"
#import "WebviewJavaScriptChannelHandler.h"

static NSString *const CHANNEL_NAME = @"webview_flutter";

@interface FWFWebViewFactory : NSObject <FlutterPlatformViewFactory>
@property(nonatomic, weak) FWFInstanceManager *instanceManager;

- (instancetype)initWithManager:(FWFInstanceManager *)manager;
@end

@implementation FWFWebViewFactory
- (instancetype)initWithManager:(FWFInstanceManager *)manager {
  self = [self init];
  if (self) {
    _instanceManager = manager;
  }
  return self;
}

- (NSObject<FlutterMessageCodec> *)createArgsCodec {
  return [FlutterStandardMessageCodec sharedInstance];
}

- (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame
                                    viewIdentifier:(int64_t)viewId
                                         arguments:(id _Nullable)args {
  NSNumber *identifier = (NSNumber *)args;
  FWFWebView *webView =
      (FWFWebView *)[self.instanceManager instanceForIdentifier:identifier.longValue];
  webView.frame = frame;
  return webView;
}

@end

@interface FLTWebViewFlutterPlugin() <WKNavigationDelegate, UIScrollViewDelegate, WKUIDelegate> {
    BOOL _enableAppScheme;
    BOOL _enableZoom;
    NSString* _invalidUrlRegex;
    NSMutableSet* _javaScriptChannelNames;
    NSNumber*  _ignoreSSLErrors;
}
@end

@implementation FLTWebViewFlutterPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    channel = [FlutterMethodChannel
               methodChannelWithName:CHANNEL_NAME
               binaryMessenger:[registrar messenger]];
  FWFInstanceManager *instanceManager =
      [[FWFInstanceManager alloc] initWithDeallocCallback:^(long identifier) {
        FWFObjectFlutterApiImpl *objectApi = [[FWFObjectFlutterApiImpl alloc]
            initWithBinaryMessenger:registrar.messenger
                    instanceManager:[[FWFInstanceManager alloc] init]];

        dispatch_async(dispatch_get_main_queue(), ^{
          [objectApi disposeObjectWithIdentifier:identifier
                                      completion:^(FlutterError *error) {
                                        NSAssert(!error, @"%@", error);
                                      }];
        });
      }];
  SetUpFWFWKHttpCookieStoreHostApi(
      registrar.messenger,
      [[FWFHTTPCookieStoreHostApiImpl alloc] initWithInstanceManager:instanceManager]);
  SetUpFWFWKNavigationDelegateHostApi(
      registrar.messenger,
      [[FWFNavigationDelegateHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
                                                        instanceManager:instanceManager
                                                            channelData:channel
                                                        invalidUrlRegex:_invalidUrlRegex
                                                        enableAppScheme:&_enableAppScheme]);
  SetUpFWFNSObjectHostApi(registrar.messenger,
                          [[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager]);
  SetUpFWFWKPreferencesHostApi(registrar.messenger, [[FWFPreferencesHostApiImpl alloc]
                                                        initWithInstanceManager:instanceManager]);
  SetUpFWFWKScriptMessageHandlerHostApi(
      registrar.messenger,
      [[FWFScriptMessageHandlerHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
                                                          instanceManager:instanceManager]);
  SetUpFWFUIScrollViewHostApi(registrar.messenger, [[FWFScrollViewHostApiImpl alloc]
                                                       initWithInstanceManager:instanceManager]);
  SetUpFWFWKUIDelegateHostApi(registrar.messenger, [[FWFUIDelegateHostApiImpl alloc]
                                                       initWithBinaryMessenger:registrar.messenger
                                                               instanceManager:instanceManager]);
  SetUpFWFUIViewHostApi(registrar.messenger,
                        [[FWFUIViewHostApiImpl alloc] initWithInstanceManager:instanceManager]);
  SetUpFWFWKUserContentControllerHostApi(
      registrar.messenger,
      [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]);
  SetUpFWFWKWebsiteDataStoreHostApi(
      registrar.messenger,
      [[FWFWebsiteDataStoreHostApiImpl alloc] initWithInstanceManager:instanceManager]);
  SetUpFWFWKWebViewConfigurationHostApi(
      registrar.messenger,
      [[FWFWebViewConfigurationHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
                                                          instanceManager:instanceManager]);
  SetUpFWFWKWebViewHostApi(registrar.messenger, [[FWFWebViewHostApiImpl alloc]
                                                    initWithBinaryMessenger:registrar.messenger
                                                            instanceManager:instanceManager]);
  SetUpFWFNSUrlHostApi(registrar.messenger,
                       [[FWFURLHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
                                                          instanceManager:instanceManager]);
  SetUpFWFUIScrollViewDelegateHostApi(
      registrar.messenger,
      [[FWFScrollViewDelegateHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
                                                        instanceManager:instanceManager]);
  SetUpFWFNSUrlCredentialHostApi(
      registrar.messenger,
      [[FWFURLCredentialHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
                                                   instanceManager:instanceManager]);

  FWFWebViewFactory *webviewFactory = [[FWFWebViewFactory alloc] initWithManager:instanceManager];
  [registrar registerViewFactory:webviewFactory withId:@"plugins.flutter.io/webview"];

    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    FLTWebViewFlutterPlugin* instance = [[FLTWebViewFlutterPlugin alloc] initWithViewController:viewController];
    [registrar addMethodCallDelegate:instance channel:channel];
    
  // InstanceManager is published so that a strong reference is maintained.
  [registrar publish:instanceManager];
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"launch" isEqualToString:call.method]) {
        if (!self.webview)
            [self initWebview:call withResult:result];
        else
            [self navigate:call];
        result(nil);
    } else if ([@"close" isEqualToString:call.method]) {
        [self closeWebView];
        result(nil);
    } else if ([@"eval" isEqualToString:call.method]) {
        [self evalJavascript:call completionHandler:^(NSString * response) {
            result(response);
        }];
    } else if ([@"resize" isEqualToString:call.method]) {
        [self resize:call];
        result(nil);
    } else if ([@"reloadUrl" isEqualToString:call.method]) {
        [self reloadUrl:call];
        result(nil);
    } else if ([@"show" isEqualToString:call.method]) {
        [self show];
        result(nil);
    } else if ([@"hide" isEqualToString:call.method]) {
        [self hide];
        result(nil);
    } else if ([@"stopLoading" isEqualToString:call.method]) {
        [self stopLoading];
        result(nil);
    } else if ([@"cleanCookies" isEqualToString:call.method]) {
        [self cleanCookies:result];
    } else if ([@"back" isEqualToString:call.method]) {
        [self back];
        result(nil);
    } else if ([@"forward" isEqualToString:call.method]) {
        [self forward];
        result(nil);
    } else if ([@"reload" isEqualToString:call.method]) {
        [self reload];
        result(nil);
    } else if ([@"canGoBack" isEqualToString:call.method]) {
        [self onCanGoBack:call result:result];
    } else if ([@"canGoForward" isEqualToString:call.method]) {
        [self onCanGoForward:call result:result];
    } else if ([@"cleanCache" isEqualToString:call.method]) {
        [self cleanCache:result];
    } else {
        result(FlutterMethodNotImplemented);
    }
}

- (void)closeWebView {
    if (self.webview != nil) {
        [self.webview stopLoading];
        [self.webview removeFromSuperview];
        self.webview.navigationDelegate = nil;
        [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
        self.webview = nil;
        // manually trigger onDestroy
        [channel invokeMethod:@"onDestroy" arguments:nil];
    }
}

- (void)initWebview:(FlutterMethodCall*)call withResult:(FlutterResult)result {
    NSNumber *clearCache = call.arguments[@"clearCache"];
    NSNumber *clearCookies = call.arguments[@"clearCookies"];
    NSNumber *hidden = call.arguments[@"hidden"];
    NSDictionary *rect = call.arguments[@"rect"];
    _enableAppScheme = call.arguments[@"enableAppScheme"];
    NSString *userAgent = call.arguments[@"userAgent"];
    NSNumber *withZoom = call.arguments[@"withZoom"];
    NSNumber *scrollBar = call.arguments[@"scrollBar"];
    NSNumber *withJavascript = call.arguments[@"withJavascript"];
    _invalidUrlRegex = call.arguments[@"invalidUrlRegex"];
    _ignoreSSLErrors = call.arguments[@"ignoreSSLErrors"];
    _javaScriptChannelNames = [[NSMutableSet alloc] init];
    
    WKUserContentController* userContentController = [[WKUserContentController alloc] init];
    if ([call.arguments[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
        NSArray* javaScriptChannelNames = call.arguments[@"javascriptChannelNames"];
        [_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
        [self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
    }

    if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
        [[NSURLCache sharedURLCache] removeAllCachedResponses];
        [self cleanCache:result];

    }

    if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (NSHTTPCookie *cookie in [storage cookies])
        {
            [storage deleteCookie:cookie];
        }

        [self cleanCookies:result];

    }

    if (userAgent != (id)[NSNull null]) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
    }

    CGRect rc;
    if (rect != nil) {
        rc = [self parseRect:rect];
    } else {
        rc = self.viewController.view.bounds;
    }

    WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = userContentController;
    self.webview = [[WKWebView alloc] initWithFrame:rc configuration:configuration];
    self.webview.UIDelegate = self;
    self.webview.navigationDelegate = self;
    self.webview.scrollView.delegate = self;
    self.webview.hidden = [hidden boolValue];
    self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
    self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
    
    [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];

    WKPreferences* preferences = [[self.webview configuration] preferences];
    if ([withJavascript boolValue]) {
        [preferences setJavaScriptEnabled:YES];
    } else {
        [preferences setJavaScriptEnabled:NO];
    }

    _enableZoom = [withZoom boolValue];

    UIViewController* presentedViewController = self.viewController.presentedViewController;
    UIViewController* currentViewController = presentedViewController != nil ? presentedViewController : self.viewController;
    [currentViewController.view addSubview:self.webview];

    [self navigate:call];
}

- (void)evalJavascript:(FlutterMethodCall*)call
     completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
    if (self.webview != nil) {
        NSString *code = call.arguments[@"code"];
        [self.webview evaluateJavaScript:code
                       completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            completionHandler([NSString stringWithFormat:@"%@", response]);
        }];
    } else {
        completionHandler(nil);
    }
}

- (void)navigate:(FlutterMethodCall*)call {
    if (self.webview != nil) {
            NSString *url = call.arguments[@"url"];
            NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
            if ( [withLocalUrl boolValue]) {
                NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
                NSString *localUrlScope = call.arguments[@"localUrlScope"];
                if (@available(iOS 9.0, *)) {
                    if(localUrlScope == nil) {
                        [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
                    }
                    else {
                        NSURL *scopeUrl = [NSURL fileURLWithPath:localUrlScope];
                        [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:scopeUrl];
                    }
                } else {
                    @throw @"not available on version earlier than ios 9.0";
                }
            } else {
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
                NSDictionary *headers = call.arguments[@"headers"];

                if (headers != nil) {
                    [request setAllHTTPHeaderFields:headers];
                }

                [self.webview loadRequest:request];
            }
        }
}

- (void)resize:(FlutterMethodCall*)call {
    if (self.webview != nil) {
        NSDictionary *rect = call.arguments[@"rect"];
        CGRect rc = [self parseRect:rect];
        self.webview.frame = rc;
    }
}

- (void)reloadUrl:(FlutterMethodCall*)call {
    if (self.webview != nil) {
        NSString *url = call.arguments[@"url"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        NSDictionary *headers = call.arguments[@"headers"];
        
        if (headers != nil) {
            [request setAllHTTPHeaderFields:headers];
        }
        
        [self.webview loadRequest:request];
    }
}

- (void)show {
    if (self.webview != nil) {
        self.webview.hidden = false;
    }
}

- (void)hide {
    if (self.webview != nil) {
        self.webview.hidden = true;
    }
}
- (void)stopLoading {
    if (self.webview != nil) {
        [self.webview stopLoading];
    }
}
- (void)back {
    if (self.webview != nil) {
        [self.webview goBack];
    }
}

- (void)onCanGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
  BOOL canGoBack = [self.webview canGoBack];
  result([NSNumber numberWithBool:canGoBack]);
}

- (void)onCanGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
  BOOL canGoForward = [self.webview canGoForward];
  result([NSNumber numberWithBool:canGoForward]);
}

- (void)forward {
    if (self.webview != nil) {
        [self.webview goForward];
    }
}
- (void)reload {
    if (self.webview != nil) {
        [self.webview reload];
    }
}

- (void)cleanCookies:(FlutterResult)result {
    if(self.webview != nil) {
        [[NSURLSession sharedSession] resetWithCompletionHandler:^{
        }];
        if (@available(iOS 9.0, *)) {
          NSSet<NSString *> *websiteDataTypes = [NSSet setWithObject:WKWebsiteDataTypeCookies];
          WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];

          void (^deleteAndNotify)(NSArray<WKWebsiteDataRecord *> *) =
              ^(NSArray<WKWebsiteDataRecord *> *cookies) {
                [dataStore removeDataOfTypes:websiteDataTypes
                              forDataRecords:cookies
                           completionHandler:^{
                            result(nil);
                           }];
              };

          [dataStore fetchDataRecordsOfTypes:websiteDataTypes completionHandler:deleteAndNotify];
        } else {
          // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
          NSLog(@"Clearing cookies is not supported for Flutter WebViews prior to iOS 9.");
        }
    }
}

- (void)cleanCache:(FlutterResult)result {
    if (self.webview != nil) {
       if (@available(iOS 9.0, *)) {
          NSSet* cacheDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
          WKWebsiteDataStore* dataStore = [WKWebsiteDataStore defaultDataStore];
          NSDate* dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
          [dataStore removeDataOfTypes:cacheDataTypes
                         modifiedSince:dateFrom
                     completionHandler:^{
              result(nil);
                     }];
        } else {
          // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
          NSLog(@"Clearing cache is not supported for Flutter WebViews prior to iOS 9.");
        }
    }
}

- (void)registerJavaScriptChannels:(NSSet*)channelNames
                        controller:(WKUserContentController*)userContentController {
    for (NSString* channelName in channelNames) {
        FLTCommunityJavaScriptChannel* _channel =
        [[FLTCommunityJavaScriptChannel alloc] initWithMethodChannel: channel
                                      javaScriptChannelName:channelName];
        [userContentController addScriptMessageHandler:_channel name:channelName];
        NSString* wrapperSource = [NSString
                                   stringWithFormat:@"window.%@ = webkit.messageHandlers.%@;", channelName, channelName];
        WKUserScript* wrapperScript =
        [[WKUserScript alloc] initWithSource:wrapperSource
                               injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                            forMainFrameOnly:NO];
        [userContentController addUserScript:wrapperScript];
    }
}

- (CGRect)parseRect:(NSDictionary *)rect {
    return CGRectMake([[rect valueForKey:@"left"] doubleValue],
                      [[rect valueForKey:@"top"] doubleValue],
                      [[rect valueForKey:@"width"] doubleValue],
                      [[rect valueForKey:@"height"] doubleValue]);
}

- (bool)checkInvalidUrl:(NSURL*)url {
  NSString* urlString = url != nil ? [url absoluteString] : nil;
  if (![_invalidUrlRegex isEqual:[NSNull null]] && urlString != nil) {
    NSError* error = NULL;
    NSRegularExpression* regex =
        [NSRegularExpression regularExpressionWithPattern:_invalidUrlRegex
                                                  options:NSRegularExpressionCaseInsensitive
                                                    error:&error];
    NSTextCheckingResult* match = [regex firstMatchInString:urlString
                                                    options:0
                                                      range:NSMakeRange(0, [urlString length])];
    return match != nil;
  } else {
    return false;
  }
}

static NSString *payReturnUrl;//支付返回页面

//#pragma mark -- WkWebView Delegate
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
//    decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//
//    NSURL *requestURL =  navigationAction.request.URL;
//    //设置微信支付跳转问题
//    //易联盟生产
//    NSString *chinaumsUrl = @"qr.chinaums.com";
//    NSString *chinaumsRedirectUrl = @"eshore.qr.chinaums.com://";
//
//    //cmpark生产
//    NSString *cmparkUrl = @"app.park.cmskcrm.com";
//    NSString *cmparkRedirectUrl = @"eshore.app.park.cmskcrm.com://";
//    //cmpark测试
//    NSString *cmparkTestUrl = @"app.park.ylmo2o.com";
//    NSString *cmparkTestRedirectUrl = @"eshore.app.park.ylmo2o.com://";
//
//    NSString *urlString = requestURL.absoluteString;
//    urlString = [urlString stringByRemovingPercentEncoding];
//
//    if ([urlString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"]) { // 处理微信支付返回APP问题
//        NSString *newRedirectUrl;//返回地址
//
//        //易联盟的支付（物管交费）
//        NSRange range=[urlString rangeOfString:chinaumsUrl];
//        if(range.location!=NSNotFound){
//            newRedirectUrl = chinaumsRedirectUrl;
//        }
//
//        //cmpark的生产支付（停车办理，临停缴费）
//        range=[urlString rangeOfString:cmparkUrl];
//        if(range.location!=NSNotFound){
//            newRedirectUrl = cmparkRedirectUrl;
//        }
//        //cmpark的测试支付（停车办理，临停缴费）
//        range=[urlString rangeOfString:cmparkTestUrl];
//        if(range.location!=NSNotFound){
//            newRedirectUrl = cmparkTestRedirectUrl;
//        }
//
//        //需要跳转回APP
//        if(newRedirectUrl!=NULL){
//            //判断是否已经添加过返回跳转地址
//            range=[urlString rangeOfString:newRedirectUrl];
//            if(range.location==NSNotFound){
//                urlString = [urlString stringByReplacingOccurrencesOfString:@"redirect_url=" withString:[@"redirect_url=" stringByAppendingString:newRedirectUrl]];
//            }
//            //设置返回的加载页面
//            range=[urlString rangeOfString:newRedirectUrl];
//            if(range.location!=NSNotFound){
//                payReturnUrl = [urlString substringFromIndex:range.location+newRedirectUrl.length];
//                payReturnUrl = [payReturnUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            }
//            urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            requestURL = [NSURL URLWithString:urlString];
//            NSDictionary *header = navigationAction.request.allHTTPHeaderFields;
//            if (header[@"Referer"] && [header[@"Referer"] isEqualToString:newRedirectUrl]) { // 如果已经设置过referer
//                // 允许跳转
//                decisionHandler(WKNavigationActionPolicyAllow);
//                return;
//            } else {
//                //                 设置referer
//                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
//                        [request setHTTPMethod:@"GET"];
//                        [request setValue:newRedirectUrl forHTTPHeaderField: @"Referer"];
//                        [webView loadRequest:request];
//                    });
//                });
//                decisionHandler(WKNavigationActionPolicyCancel);
//                return;
//            }
//        }else{
//            NSLog(@"%@", @"未适配的支付");
//            NSLog(@"%@", requestURL.absoluteString);
//        }
//    }else if ([urlString hasPrefix:chinaumsRedirectUrl]
//              ||[urlString hasPrefix:cmparkRedirectUrl]
//              ||[urlString hasPrefix:cmparkTestRedirectUrl]) {
//        //微信支付跳转返回的页面
//        NSString *loadUrl= urlString;
//        //已经适配的微信支付跳转返回的页面
//        if(payReturnUrl!=NULL){
//            loadUrl = payReturnUrl;
//            payReturnUrl =NULL;
//        }
//
//        loadUrl = [loadUrl stringByReplacingOccurrencesOfString:chinaumsRedirectUrl withString:@""];
//        loadUrl = [loadUrl stringByReplacingOccurrencesOfString:cmparkRedirectUrl withString:@""];
//        loadUrl = [loadUrl stringByReplacingOccurrencesOfString:cmparkTestRedirectUrl withString:@""];
//
//        loadUrl = [loadUrl  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        requestURL = [NSURL URLWithString:loadUrl];
//        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
//        [request setHTTPMethod:@"GET"];
//        [webView loadRequest:request];
//
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;
//    }
//    if (requestURL != nil) {
//        if ([requestURL.scheme isEqualToString:@"weixin"]) {    //处理微信支付
//            [self weixinCatchEvent:requestURL];
//            decisionHandler(WKNavigationActionPolicyCancel);
//            return;
//        } else if ([requestURL.scheme isEqualToString:@"alipays"] || [requestURL.scheme isEqualToString:@"alipay"]) {       //处理支付宝支付
//            [self zhifubaoCatchEvent:requestURL];
//        } else if ([requestURL.scheme isEqualToString:@"intent"]) {
//            if ([requestURL.host isEqualToString:@"platformapi"] && [requestURL.relativePath isEqualToString:@"/startapp"]) {       //处理老版本支付宝支付
//                [self zhifubaoCatchEvent:requestURL];
//            }
//        }
//    }
//
//    NSString *_webUrlStr = navigationAction.request.URL.absoluteString;
//    NSString *lastName =[[_webUrlStr lastPathComponent] lowercaseString];
//    if ([lastName containsString:@".pdf"])
//    {
//        NSData *data = [NSData dataWithContentsOfURL:navigationAction.request.URL];
//        [self.webview loadData:data MIMEType:@"application/pdf" characterEncodingName:@"GBK" baseURL:nil];
//    }
//
//    BOOL isInvalid = [self checkInvalidUrl: navigationAction.request.URL];
//    
//    id data = @{@"url": navigationAction.request.URL.absoluteString,
//                @"type": isInvalid ? @"abortLoad" : @"shouldStart",
//                @"navigationType": [NSNumber numberWithInteger:navigationAction.navigationType]};
//    [channel invokeMethod:@"onState" arguments:data];
//
//    if (navigationAction.navigationType == WKNavigationTypeBackForward) {
//        [channel invokeMethod:@"onBackPressed" arguments:nil];
//    } else if (!isInvalid) {
//        id data = @{@"url": navigationAction.request.URL.absoluteString};
//        [channel invokeMethod:@"onUrlChanged" arguments:data];
//    }
//
//    if (_enableAppScheme ||
//        ([webView.URL.scheme isEqualToString:@"http"] ||
//         [webView.URL.scheme isEqualToString:@"https"] ||
//         [webView.URL.scheme isEqualToString:@"about"] ||
//         [webView.URL.scheme isEqualToString:@"file"])) {
//         if (isInvalid) {
//            decisionHandler(WKNavigationActionPolicyCancel);
//         } else {
//            decisionHandler(WKNavigationActionPolicyAllow);
//         }
//    } else {
//        decisionHandler(WKNavigationActionPolicyCancel);
//    }
//}

- (void)weixinCatchEvent:(NSURL *)url {
    if ([url.host isEqualToString:@"wap"]) {
        if ([url.relativePath isEqualToString:@"/pay"]) {
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                if ( @available(iOS 10.0, *) ) {
                    [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly : [NSNumber numberWithBool:NO]} completionHandler:^(BOOL success) {

                    }];
                } else {
                    [[UIApplication sharedApplication] openURL:url];
                }
            } else {
                NSString *title = @"未检测到微信，请安装后重试";
                [self showAlertController:[UIApplication sharedApplication].keyWindow.rootViewController title:title message:nil cancelTilte:@"好" otherTitleArray:nil];
            }
        }
    }
}

- (void)zhifubaoCatchEvent:(NSURL *)url {
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        if ( @available(iOS 10.0, *) ) {
            [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly : [NSNumber numberWithBool:NO]} completionHandler:^(BOOL success) {

            }];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    } else {
        // 下面两行代码 是修改 title颜色和字体的代码
        NSString *title = @"未检测到支付宝，请安装后重试";
        [self showAlertController:[UIApplication sharedApplication].keyWindow.rootViewController title:title message:nil cancelTilte:@"好" otherTitleArray:nil];
    }
}

//alert封装
- (void)showAlertController:(UIViewController *)viewController
                      title:(NSString *)title
                    message:(NSString *)message
                cancelTilte:(NSString *)cancelTitle
            otherTitleArray:(NSArray *)otherTitleArray {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    // 下面两行代码 是修改 title颜色和字体的代码
    NSAttributedString *attributedMessage = [[NSAttributedString alloc] initWithString:title attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10.0f], NSForegroundColorAttributeName:[UIColor blackColor]}];
    [alert setValue:attributedMessage forKey:@"attributedTitle"];
    if (cancelTitle) {
        // 取消
        UIAlertAction  *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:cancelAction];
    }

    if (otherTitleArray.count>0) {
        for (NSInteger i = 0; i<otherTitleArray.count; i++) {

            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherTitleArray[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            }];
            // [action setValue:[UIColor redColor] forKey:@"titleTextColor"]; // 此代码 可以修改按钮颜色
            [alert addAction:otherAction];
        }

    }

    [viewController presentViewController:alert animated:YES completion:nil];

}

- (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
  [registrar publish:[NSNull null]];
}
@end
